package net.cmkj.mine.core.admin.service;

import com.jfinal.aop.Inject;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import net.cmkj.mine.common.anno.RequiresPermissions;
import net.cmkj.mine.common.controller.BaseController;
import net.cmkj.mine.common.model.InvokeResult;
import net.cmkj.mine.core.admin.module.ModulesService;
import net.cmkj.mine.util.IWebUtils;
import net.cmkj.mine.util.StringUtil;

import java.io.*;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;

public class MineController extends BaseController {

    @Inject
    private MineService service;

    @Inject
    private ModulesService modulesService;

    @RequiresPermissions(value = {"/mineservice"})
    public void index() throws Exception {
        String moduleurl = getPara("moduleurl");
        setAttr("moduleurl", moduleurl);
        setAttr("module", modulesService.getModuleByUrl(moduleurl));
        render("serviceList.html");
    }

    @RequiresPermissions(value = {"/mineservice"})
    public void getPaginateList() throws Exception {
        String moduleurl = getPara("moduleurl");
        renderJson(service.getList(getPage(), getRows(), moduleurl, getRequest(), getOrderbyStr()));
    }

    @RequiresPermissions(value = {"/mineservice"})
    public void getList() throws Exception {
        String moduleurl = getPara("moduleurl");
        renderJson(service.getList(moduleurl, getRequest(), getOrderbyStr()));
    }

    @RequiresPermissions(value = {"/mineservice"})
    public void showColumns() throws Exception {
        long moduleid = getParaToLong("moduleid");
        renderJson(service.showColumns(moduleid));
    }

    @RequiresPermissions(value = {"/mineservice"})
    public void showSearchs() throws Exception {
        long moduleid = getParaToLong("moduleid");
        renderJson(service.getSearchedList(modulesService.findById(moduleid)));
    }

    @RequiresPermissions(value = {"/mineservice"})
    public void getSelectData() throws Exception {
        long moduleid = getParaToLong("foreignTable");
        String foreignKey = getPara("foreignKey");
        renderJson(service.getSelectData(moduleid, foreignKey));
    }

    @RequiresPermissions(value = {"/mineservice"})
    public void form() throws Exception {
        String tablename = getPara("tablename");
        if(getPara("type")==null){
            setAttr("type", 0);
        }else{
            setAttr("type", 1);
        }
        Long id = getParaToLong("id");
        if (id != null) {
            setAttr("item", JsonKit.toJson(service.findById(tablename, id)));
        } else {
            setAttr("item", JsonKit.toJson(new Record()));
        }
        setAttr("id", id);
        setAttr("tablename", tablename);
        setAttr("moduleid", getPara("moduleid"));
        render("serviceForm.html");
    }

    @RequiresPermissions(value = {"/mineservice"})
    public void findById() throws Exception {
        String tablename = getPara("tablename");
        Long id = getParaToLong("id");
        renderJson(service.findById(tablename, id));
    }

    @RequiresPermissions(value = {"/mineservice"})
    public void save() throws Exception {
        String tablename = getPara("tablename");
        Map<String, String[]> params = getParaMap();
        renderJson(service.save(tablename, params, IWebUtils.getCurrentSysUser(getRequest())));
    }

    @RequiresPermissions(value = {"/mineservice"})
    public void delete() throws Exception {
        String ids = getPara("ids");
        String tablename = getPara("tablename");
        renderJson(service.delete(tablename, ids));
    }

    @RequiresPermissions(value = {"/mineservice"})
    public void deleteFile() throws Exception {
        String ids = getPara("ids");
        String tablename = getPara("tablename");
        renderJson(service.deleteFile(tablename, ids));
    }

    @RequiresPermissions(value = {"/mineservice"})
    public void attachList() throws Exception {
        setAttr("tablename", getPara("tablename"));
        setAttr("parentid", getPara("parentid"));
        render("attachList.html");
    }

    @RequiresPermissions(value = {"/mineservice"})
    public void getAttachList() throws Exception {
        String tablename = getPara("tablename");
        long parentid = getParaToLong("parentid");
        renderJson(service.getAttachList(tablename, parentid));
    }

    @RequiresPermissions(value = {"/mineservice"})
    public void uploadForm() throws Exception {
        setAttr("tablename", getPara("tablename"));
        setAttr("parentid", getPara("parentid"));
        render("uploadForm.html");
    }

    @RequiresPermissions(value = {"/mineservice"})
    public void uploadFile() throws Exception {
        String tablename = getPara("tablename");
        long parentid = getParaToLong("parentid");
        String path = PathKit.getWebRootPath()+"/upload/"+tablename;
        UploadFile file = getFile("file", "temp");
        File source = file.getFile();
        String fileName = file.getFileName();
        String uuid = StringUtil.getUUID()+fileName.substring(fileName.lastIndexOf("."));
        try {
            File targetDir = new File(path);
            if (!targetDir.exists()) {
                targetDir.mkdirs();
            }
            File target = new File(targetDir, uuid);
            if (!target.exists()) {
                target.createNewFile();
            }
            /*
            FileOutputStream fos = new FileOutputStream(target);
            byte[] bts = new byte[1024];
            while (fis.read(bts, 0, 1024) != -1) {
                fos.write(bts, 0, 1024);
            }
            fos.close();
            fis.close();
            */
            FileChannel inputChannel = new FileInputStream(source).getChannel();
            FileChannel outputChannel = new FileOutputStream(target).getChannel();
            outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
            inputChannel.close();
            outputChannel.close();
            service.attachSave(tablename, fileName, uuid, parentid);
            source.delete();
        } catch (FileNotFoundException e) {
            renderJson(InvokeResult.failure("上传出现错误，请稍后再上传"));
        } catch (IOException e) {
            renderJson(InvokeResult.failure("文件写入服务器出现错误，请稍后再上传"));
        }
        renderJson(InvokeResult.success());
    }

    @RequiresPermissions(value = {"/mineservice"})
    public void fileDownload() throws Exception {
        String tablename = getPara("tablename");
        long id = getParaToLong("id");
        String path = PathKit.getWebRootPath()+"/upload/"+tablename+"/";
        Record attach = service.getAttach(tablename, id);
        renderFile(new File(path+attach.getStr("realname")), attach.getStr("name"));
    }

    @RequiresPermissions(value = {"/mineservice"})
    public void tableFileDownload() throws Exception {
        String name = getPara("name");
        String url = getPara("url");
        renderFile(new File(PathKit.getWebRootPath()+url), name);
    }

    @RequiresPermissions(value = {"/mineservice"})
    public void importForm() throws Exception {
        setAttr("moduleid", getPara("moduleid"));
        setAttr("tablename", getPara("tablename"));
        render("import.html");
    }

    @RequiresPermissions(value = {"/mineservice"})
    public void importExcel() throws Exception {
        long moduleid = getParaToLong("moduleid");
        UploadFile up = getFile();
        Integer type = getParaToInt("type");
        renderJson(service.importExcel(moduleid,type, up, IWebUtils.getCurrentSysUser(getRequest())));
    }

    @RequiresPermissions(value = {"/mineservice"})
    public void exportExcel() throws Exception {
        long moduleid = getParaToLong("moduleid");
        String tablename = getPara("tablename");
        int type = getParaToInt("type");
        service.exportExcel(moduleid, tablename, type, getOrderbyStr(), getRequest(), getResponse());
        renderNull();
    }

    @RequiresPermissions(value= {"/mineservice"})
    public void uploadfile() throws Exception {
        String tablename = getPara("tablename");
        String path = PathKit.getWebRootPath()+"/upload/"+tablename;
        UploadFile file = getFile("file", "temp");
        File source = file.getFile();
        String fileName = file.getFileName();
        String uuid = StringUtil.getUUID()+fileName.substring(fileName.lastIndexOf("."));
        try {
            File targetDir = new File(path);
            if (!targetDir.exists()) {
                targetDir.mkdirs();
            }
            File target = new File(targetDir, uuid);
            if (!target.exists()) {
                target.createNewFile();
            }
           /*
           FileOutputStream fos = new FileOutputStream(target);
            byte[] bts = new byte[1024];
            while (fis.read(bts, 0, 1024) != -1) {
                fos.write(bts, 0, 1024);
            }
            fos.close();
            fis.close();
            */
            FileChannel inputChannel = new FileInputStream(source).getChannel();
            FileChannel outputChannel = new FileOutputStream(target).getChannel();
            outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
            inputChannel.close();
            outputChannel.close();
            source.delete();
        } catch (FileNotFoundException e) {
            renderJson(InvokeResult.failure("上传出现错误，请稍后再上传"));
            e.printStackTrace();
        } catch (IOException e) {
            renderJson(InvokeResult.failure("文件写入服务器出现错误，请稍后再上传"));
            e.printStackTrace();
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("success", 1);
        result.put("message", "上传成功！");
        result.put("url", getRequest().getContextPath()+"/upload/"+tablename+"/"+uuid);
        result.put("name", file.getFileName());
        renderJson(result);
    }

}
